package com.zf.yichat.api.controller.trend;

import com.zf.yichat.api.controller.BaseController;
import com.zf.yichat.api.dto.request.*;
import com.zf.yichat.mapper.TrendConfigMapper;
import com.zf.yichat.model.SysDict;
import com.zf.yichat.model.SysDictData;
import com.zf.yichat.model.Trend;
import com.zf.yichat.model.TrendConfig;
import com.zf.yichat.service.FriendService;
import com.zf.yichat.service.SysDictService;
import com.zf.yichat.service.TrendService;
import com.zf.yichat.utils.YiChatMsgCode;
import com.zf.yichat.utils.common.DtoChangeUtils;
import com.zf.yichat.utils.common.N3d;
import com.zf.yichat.utils.response.FsPage;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import com.zf.yichat.vo.ApiConst;
import com.zf.yichat.vo.DictKey;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.internal.util.Contracts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

/**
 * 一句话描述功能
 *
 * @author fengsong
 * @date create in 16:44 2019/6/5 2019
 */
@RestController
@RequestMapping("trend")
public class TrendController extends BaseController {


    @Autowired
    private TrendService trendService;

    @Autowired
    private FriendService friendService;

    @Autowired
    private SysDictService sysDictService;

    @Resource
    private TrendConfigMapper trendConfigMapper;

    /**
     * 发布动态
     */
    @PostMapping("/publish")
    public FsResponse publish(@RequestBody TrendPublishRequest params) {

//        String admins=          Optional.ofNullable(sysDictService.selectOne(DictKey.trend_admin)).map(SysDict::getMemo).orElse(null);
//          if(admins==null){
//
//              return FsResponseGen.failMsg("无发布权限");
//          }
//        if(!admins.contains(getUserId()+"")){
//            return FsResponseGen.failMsg("无发布权限");
//        }

        params.valid();
        return trendService.add(params.getContent(), params.getImgs(), params.getVideos(), params.getLocation(), getUserId(), params.getSign());
    }

    /**
     * 根据不同类型发布动态
     */
    @PostMapping("/publishForType")
    public FsResponse publishForType(@RequestBody TrendPublishRequest params) {
        params.valid();

        // 发布动态不需要设置权限
        String sign = params.getSign();
        if (Trend.SIGN_TRENDS.equals(sign)) {
            return trendService.publishForType(params.getContent(), params.getImgs(), params.getVideos(),
                    params.getLocation(), getUserId(), params.getSign(), params.getSubjectTitle(), params.getInformationDesc());
        }

        String admins= Optional.ofNullable(sysDictService.selectOne(DictKey.trend_admin)).map(SysDict::getMemo).orElse(null);
        if(admins == null){
             return FsResponseGen.failMsg("无发布权限");
         }
        if(!admins.contains(getUserId()+"")){
             return FsResponseGen.failMsg("无发布权限");
        }
        return trendService.publishForType(params.getContent(), params.getImgs(), params.getVideos(),
                params.getLocation(), getUserId(), params.getSign(), params.getSubjectTitle(), params.getInformationDesc());
    }

    @PostMapping("/admins")
    public FsResponse isAdmins(@RequestBody TrendPublishRequest params) {
        String admins=          Optional.ofNullable(sysDictService.selectOne(DictKey.trend_admin)).map(SysDict::getMemo).orElse(null);
        if(admins==null){

            return FsResponseGen.failMsg("无发布权限");
        }
        if(!admins.contains(getUserId()+"")){
            return FsResponseGen.failMsg("无发布权限");
        }

        return FsResponseGen.successData("有发布权限");

     }

    /**
     * 删除动态
     */
    @PostMapping("/delete")
    public FsResponse delete(@RequestBody TrendDeleteRequest params) {

        params.valid();
        Trend trend = trendService.selectById(params.getTrendId());
        Contracts.assertTrue(trend.getUserId().compareTo(getUserId()) == 0, YiChatMsgCode.TREND_DELETE_AUTH.msg());

        trendService.delete(params.getTrendId());
        return FsResponseGen.success();
    }

    /**
     * 动态列表
     */
    @PostMapping("/list")
    public FsResponse list(@RequestBody TrendListRequest params) throws Exception {
        params.valid();
        if (getUserId().compareTo(N3d.decode(params.getUserId())) != 0) {
            Contracts.assertTrue(friendService.isFriend(getUserId(), N3d.decode(params.getUserId())), YiChatMsgCode.TREND_LIST_AUTH.msg());
        }
        return trendService.selectList(FsPage.init(params.getPageNo(), params.getPageSize()), N3d.decode(params.getUserId()), getUserId());
    }

    @PostMapping("/all/list")
    public FsResponse listAll(@RequestBody TrendListRequest params) throws Exception {
        params.valid();
//        if (getUserId().compareTo(N3d.decode(params.getUserId())) != 0) {
//            Contracts.assertTrue(friendService.isFriend(getUserId(), N3d.decode(params.getUserId())), YiChatMsgCode.TREND_LIST_AUTH.msg());
//        }
        return trendService.selectList2(FsPage.init(params.getPageNo(), params.getPageSize()), N3d.decode(params.getUserId()), getUserId());
    }

    @PostMapping("/list/all")
    public FsResponse listAll2(@RequestBody TrendListRequest params) throws Exception {
        // params.valid();
//        if (getUserId().compareTo(N3d.decode(params.getUserId())) != 0) {
//            Contracts.assertTrue(friendService.isFriend(getUserId(), N3d.decode(params.getUserId())), YiChatMsgCode.TREND_LIST_AUTH.msg());
//        }
        return trendService.selectList2(FsPage.init(params.getPageNo(), params.getPageSize()), N3d.decode(params.getUserId()), getUserId());
    }


    /**
     * 动态列表
     */
    @PostMapping("/list/test")
    public FsResponse listTest(@RequestBody FsPage params) {

        System.out.println(getRequest().getHeader("token"));
        params = FsPage.init(params.getPageNo(), params.getPageSize());
        return trendService.selectList(FsPage.init(params.getPageNo(), params.getPageSize()), null, 14012445L);
    }

    /**
     * 动态详情
     */
    @PostMapping("/detail")
    public FsResponse detail(@RequestBody TrendDetailRequest params) {
        params.valid();

        return FsResponseGen.successData(trendService.detailById(params.getTrendId(), getUserId()));
    }

    /**
     * 好友动态-查询全部类型
     */
    @PostMapping("/friend/list")
    public FsResponse friendList(@RequestBody FsPage params) {

        return trendService.selectFriendList(FsPage.init(params.getPageNo(), params.getPageSize()), getUserId());
    }

    /**
     * 好友动态-排除其他特殊类型
     */
    @PostMapping("/friend/excludeOtherTypeList")
    public FsResponse excludeOtherTypeList(@RequestBody FsPage params) {

        return trendService.excludeOtherTypeList(FsPage.init(params.getPageNo(), params.getPageSize()), getUserId());
    }

    /**
     * 好友动态-增加官方发布资讯
     */
    @PostMapping("/friend/mixedOfficialList")
    public FsResponse mixedOfficialList(@RequestBody TrendTypeRequest request) {
        Integer pageNo = request.getPageNo();
        Integer pageSize = request.getPageSize();

        if (null == pageNo) {
            pageNo = 1;
        }
        if(null == pageSize){
            pageSize = 10;
        }
        String trendType = request.getTrendType();
        return trendService.mixedOfficialList(FsPage.init(pageNo, pageSize), getUserId(), trendType);
    }

    /**
     * 展示不同类型好友动态， 资讯  话题
     */
    @PostMapping("/friend/trendTypeList")
    public FsResponse trendTypeList(@RequestBody TrendTypeRequest request) {
        Integer pageNo = request.getPageNo();
        Integer pageSize = request.getPageSize();

        String trendType = request.getTrendType();
        if (StringUtils.isBlank(trendType)) {
            return FsResponseGen.failMsg("类型不能为空！");
        }
        if (null == pageNo) {
            pageNo = 1;
        }
        if(null == pageSize){
            pageSize = 10;
        }

        return trendService.trendTypeList(FsPage.init(pageNo, pageSize), trendType, getUserId());
    }

    /**
     * 话题类型-增加热度 使用trend表的权重字段表示
     */
    @PostMapping("/addTrendWeight")
    public FsResponse addTrendWeight(@RequestBody TrendDetailRequest request) {

        Long trendId = request.getTrendId();
        if (null == trendId) {
            return FsResponseGen.failMsg("参数错误，trendId不能为空！");
        }

        return trendService.addTrendWeight(trendId);
    }


    /**
     * 动态背景图
     */
    @PostMapping("background")
    public FsResponse background(@RequestBody TrendBackgroundRequest request) throws Exception {

        Long userId = getUserId();

        String requestUserId = request.getUserId();
        if (StringUtils.isNotBlank(requestUserId)) {
            userId = N3d.decode(requestUserId);
        }
        Example example = new Example(TrendConfig.class);
        example.createCriteria().andEqualTo("userId", userId);
        return FsResponseGen.successData(Optional.ofNullable(trendConfigMapper.selectOneByExample(example)).map(TrendConfig::getImg).orElse(null));
    }

    /**
     * 背景图设置
     */
    @PostMapping("background/set")
    public FsResponse backgroundSet(@RequestBody TrendBackgroundRequest request) throws Exception {

        Long userId = getUserId();

        String requestUserId = request.getUserId();
        if (StringUtils.isNotBlank(requestUserId)) {
            userId = N3d.decode(requestUserId);
        }

        Example example = new Example(TrendConfig.class);
        example.createCriteria().andEqualTo("userId", userId);

        TrendConfig config = trendConfigMapper.selectOneByExample(example);
        if (Objects.nonNull(config)) {
            config.setImg(request.getImg());
            trendConfigMapper.updateByPrimaryKeySelective(config);
        } else {
            config = new TrendConfig();
            config.setImg(request.getImg());
            config.setUserId(userId);
            trendConfigMapper.insertSelective(config);
        }
        return FsResponseGen.success();
    }


    /**
     * 动态标签
     */
    @PostMapping("/sign/list")
    public FsResponse signList() {
        return FsResponseGen.successData(DtoChangeUtils.getList(sysDictService.selectData(DictKey.friend_trend_sign), SysDictData::getValue));
    }


    /**
     * 所有用户动态
     */
    @PostMapping("/public/list")
    public FsResponse publicList(@RequestBody TrendPublicRequest params) {

        return trendService.selectPublicList(FsPage.init(params.getPageNo(), params.getPageSize()), params.getSign(), getUserId());
    }
}
